
import { useNavTagsView } from "@/pinia/modules/navTagsView";
import { useScrollTo } from "@/hooks/useScrollTo";
import { useTagsView } from "@/hooks/useTagsView";
import { RouteLocationNormalizedLoaded } from "vue-router";
import { type ElScrollbar } from "element-plus";

export default defineComponent({
  name: "NavTagsComponent",
  setup() {
    const { closeCurrent, closeLeft, closeRight, closeOthers, closeAll } =
      useTagsView();
    const { addView, setSelectedTag } = useNavTagsView();
    const navTagsViewStore = useNavTagsView();
    const router = useRouter();
    const { currentRoute, go } = useRouter();
    const visitedViewList = computed(() => navTagsViewStore.visitedViews);
    const selectedTag: any = computed(() => navTagsViewStore.selectedTag);
    const scrollbarRef = ref<ComponentRef<typeof ElScrollbar>>(),
      scrollLeftNumber = ref(0);
    onMounted(() => {
      addTags();
      initTags();
      //   moveToCurrentTag();
    });
    watch(
      () => currentRoute.value,
      () => {
        addTags();
        moveToCurrentTag();
      }
    );

    // 页面切换
    const navHandler = (route: RouteLocationNormalizedLoaded) => {
      router.push(route.fullPath);
    };
    // 添加路由到头部
    const addTags = () => {
      const { name } = unref(currentRoute);
      if (name) {
        setSelectedTag(unref(currentRoute));
        addView(unref(currentRoute));
      }
    };
    // 初始化tag
    const initTags = () => {
      //   affixTagArr.value = filterAffixTags(unref(routers));
      //   for (const tag of unref(affixTagArr)) {
      //     // Must have tag name
      //     if (tag.name) {
      //       addVisitedView(cloneDeep(tag));
      //     }
      //   }
    };
    // 是否是当前tag
    const isActive = (route: RouteLocationNormalizedLoaded): boolean => {
      return route.path === unref(currentRoute).path;
    };
    // 关闭选中的tag
    const closeSelectedTag = (view: RouteLocationNormalizedLoaded) => {
      closeCurrent(view, () => {
        if (isActive(view)) {
          go(-1);
        }
      });
    };
    // 滚动到选中的tag
    const moveToCurrentTag = async () => {
      await nextTick();
      for (const v of visitedViewList.value) {
        if (v.fullPath === unref(currentRoute).path) {
          moveToTarget(v);
          if (v.fullPath !== unref(currentRoute).fullPath) {
            // tagsViewStore.updateVisitedView(unref(currentRoute))
          }

          break;
        }
      }
    };
    const moveToTarget = (currentTag: RouteLocationNormalizedLoaded) => {
      const wrap$ = unref(scrollbarRef)?.wrapRef;

      if (visitedViewList.value[0].fullPath === currentTag.fullPath) {
        // 当前为第一条
        // 直接滚动到0的位置
        const { start } = useScrollTo({
          el: wrap$!,
          position: "scrollLeft",
          to: 0,
          duration: 500,
        });
        start();
        return;
      }
      if (
        visitedViewList.value[visitedViewList.value.length - 1].fullPath ===
        currentTag.fullPath
      ) {
        // 当前为最后一条
        // 滚动到最后的位置
        const { start } = useScrollTo({
          el: wrap$!,
          position: "scrollLeft",
          to: wrap$!.scrollWidth - wrap$!.offsetWidth,
          duration: 500,
        });
        start();
        return;
      }
      //   中间条目
      // find preTag and nextTag
      const currentIndex: number = visitedViewList.value.findIndex(
        (item: any) =>
          (item as RouteLocationNormalizedLoaded).fullPath ===
          currentTag.fullPath
      );

      const tgsRefs = document.getElementsByClassName("tab-view-box");

      const prevTag = tgsRefs[currentIndex - 1];
      const nextTag = tgsRefs[currentIndex + 1];

      // the tag's offsetLeft after of nextTag
      const afterNextTagOffsetLeft =
        nextTag.offsetLeft + nextTag.offsetWidth / 2 + 5;

      // the tag's offsetLeft before of prevTag
      const beforePrevTagOffsetLeft = prevTag.offsetLeft - 5;
      if (
        afterNextTagOffsetLeft >
        unref(scrollLeftNumber) + wrap$!.offsetWidth / 2
      ) {
        const { start } = useScrollTo({
          el: wrap$!,
          position: "scrollLeft",
          to: afterNextTagOffsetLeft - wrap$!.offsetWidth / 2,
          duration: 500,
        });
        start();
        return;
      }
      if (beforePrevTagOffsetLeft < unref(scrollLeftNumber)) {
        const { start } = useScrollTo({
          el: wrap$!,
          position: "scrollLeft",
          to: beforePrevTagOffsetLeft - prevTag.offsetWidth - 10,
          duration: 500,
        });
        start();
      }
    };
    //  监听 滚动条滚动
    const scrollHandler = ({ scrollLeft }: any) => {
      scrollLeftNumber.value = scrollLeft;
    };
    // 判断是否到最左边或者最右边
    const endReachedHandler = (val: any) => {
      console.log(val);
    };
    const moveHandler = (to: number) => {
      const wrap$ = unref(scrollbarRef)?.wrapRef;
      const { start } = useScrollTo({
        el: wrap$!,
        position: "scrollLeft",
        to: unref(scrollLeftNumber) + to,
        duration: 500,
      });
      start();
    };
    const closeHandler = (command: string) => {
      if (command === "closeCurrrent") {
        // 关闭当前
        closeSelectedTag(currentRoute.value);
      }
      if (command === "closeLeft") {
        // 关闭左侧
        closeLeft();
      }
      if (command === "closeRight") {
        // 关闭右侧
        closeRight();
      }
      if (command === "closeOthers") {
        // 关闭右侧
        closeOthers();
      }
      if (command === "closeAllTags") {
        // 关闭右侧
        closeAll();
      }
    };
    const refreshHandler = () => {
      location.reload();
    };
    return () => (
      <div class="flex  items-center">
        <p
          class="w-30px h-30px flex items-center justify-center cursor-pointer border-r border-[#eee]"
          onClick={() => moveHandler(-200)}
        >
          <el-icon size="16px">
            <arrow-left />
          </el-icon>
        </p>
        <div class="flex-1 flex items-center overflow-hidden">
          <el-scrollbar
            ref={scrollbarRef}
            class="h-full w-full"
            onEndReached={endReachedHandler}
            onScroll={scrollHandler}
            always={false}
          >
            <div class="flex h-30px mx-5px items-center">
              {visitedViewList.value.map((item: any) => (
                <router-link class="mx-3px" to={item}>
                  <el-tag class="tab-view-box"
                    key={item.fullPath}
                    closable={item.name !== "Workbench"}
                    type={
                      selectedTag.value.fullPath === item.fullPath
                        ? "primary"
                        : "info"
                    }
                    color={
                      selectedTag.value.fullPath === item.fullPath
                        ? ""
                        : "white"
                    }
                  >
                    {item.meta.title}
                  </el-tag>
                </router-link>
              ))}
            </div>
          </el-scrollbar>
        </div>
        <p
          class="w-30px h-30px flex items-center justify-center cursor-pointer border-l border-[#eee]"
          onClick={() => moveHandler(200)}
        >
          <el-icon size="16px">
            <arrow-right />
          </el-icon>
        </p>
        <p
          class="w-30px h-30px flex items-center justify-center cursor-pointer "
          onClick={() => refreshHandler()}
        >
          <el-icon size="16px">
            <refresh />
          </el-icon>
        </p>
        <el-dropdown
          trigger="click"
          placement="bottom-end"
          onCommand={closeHandler}
          v-slots={{
            default: () => (
              <p class="w-30px h-30px flex items-center justify-center cursor-pointer">
                <el-icon size="16px">
                  <grid />
                </el-icon>
              </p>
            ),
            dropdown: () => (
              <el-dropdown-menu>
                <el-dropdown-item icon="Close" command="closeCurrrent">
                  关闭当前标签页
                </el-dropdown-item>
                <el-dropdown-item icon="Back" command="closeLeft">
                  关闭左边标签页
                </el-dropdown-item>
                <el-dropdown-item icon="Right" command="closeRight">
                  关闭右边标签页
                </el-dropdown-item>
                <el-dropdown-item icon="PriceTag" command="closeOthers">
                  关闭其他标签页
                </el-dropdown-item>
                <el-dropdown-item icon="CollectionTag" command="closeAllTags">
                  关闭全部标签页
                </el-dropdown-item>
              </el-dropdown-menu>
            ),
          }}
        />
      </div>
    );
  },
});
